// pages/room/room.js

const app = getApp()
const db = wx.cloud.database()

Page({
  data: {
    roomId: null,
    roomInfo: {},
    seats: new Array(6).fill({}),
    playerWatcher: null,
    loginModalShow: false
  },
  onLoad(options) {
    this.setData({
      roomId: options.roomId
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    if (app.globalData.userInfo) {
      this.getRoomInfo(options.roomId)
    } else {
      this.getUserInfo()
    }
  },
  onShareAppMessage () {
    return {
      title: '嘟嘟的你画我猜',
      path: '/pages/room/room?roomId=' + this.data.roomId
    }
  },
  onUnload() {
    this.data.playerWatcher && this.data.playerWatcher.close()
  },
  getUserInfo () {
    wx.cloud.callFunction({
      name: 'drawsthFunctions',
      data: {
        url: 'user/getInfo'
      }
    }).then(res => {
      if (res.result) {
        const userInfo = res.result
        app.globalData.userInfo = userInfo
        this.getRoomInfo(this.data.roomId)
      } else {
        wx.hideLoading()
        this.setData({
          loginModalShow: true
        })
      }
    })
  },
  setUserInfo (e) {
    const userInfo = e.detail.userInfo
    app.globalData.userInfo = userInfo
    this.setData({
      userInfo,
      loginModalShow: false
    })
    this.getRoomInfo(this.data.roomId)
  },
  getRoomInfo(roomId) {
    wx.cloud.callFunction({
      name: 'drawsthFunctions',
      data: {
        url: 'room/getInfo',
        data: {
          roomId: roomId
        }
      }
    }).then(res => {
      const roomInfo = res.result.data
      this.setData({
        roomInfo
      })
      wx.hideLoading()
      const target = roomInfo.players.find(item => item.openid === app.globalData.userInfo.openid)
      if (target) {
        this.initWatchPlayer(roomId)
      } else {
        if (roomInfo.status === 2) {
          wx.showToast({
            title: '游戏正在进行中',
            icon: 'none',
            duration: 1500,
            mask: true
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/index/index'
            })
          }, 1500)
        } else if (roomInfo.status === 3) {
          wx.showToast({
            title: '游戏已结束',
            icon: 'none',
            duration: 1500,
            mask: true
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/index/index'
            })
          }, 1500)
        } else {
          this.addPlayer(this.data.roomId)
        }
      }
    })
  },
  addPlayer(roomId) {
    const userInfo = app.globalData.userInfo
    wx.cloud.callFunction({
      name: 'drawsthFunctions',
      data: {
        url: 'room/addPlayer',
        data: {
          roomId: roomId,
          userInfo
        }
      }
    }).then(res => {
      const roomInfo = res.result.data
      this.setData({
        roomInfo
      })
      this.initWatchPlayer(roomId)
    })
  },
  initWatchPlayer(roomId) {
    const db = wx.cloud.database()
    const playerWatcher = db.collection('room').doc(roomId).watch({
      onChange: (snapshot) => {
        // console.log(snapshot)
        // console.log('docs\'s changed events', snapshot.docChanges)
        // console.log('query result snapshot after the event', snapshot.docs)
        // console.log('is init data', snapshot.type === 'init')
        const currentRoomInfo = snapshot.docs[0]
        if (currentRoomInfo.status === 2) {
          wx.redirectTo({
            url: `/pages/paint/paint?roomId=${this.data.roomId}`
          })
          return
        }
        const currentPlayers = snapshot.docs[0].players
        const seats = this.data.seats.slice()
        currentPlayers.forEach((item, index) => {
          seats.splice(index, 1, item)
        })
        this.setData({
          seats
        })
      },
      onError: (err) => {
        console.error('the watch closed because of error', err)
      }
    })
    this.setData({
      playerWatcher
    })
  },
  startGame() {
    const players = this.data.seats.filter(item => item.openid)
    if (players.length < 2) {
      wx.showToast({
        title: '至少要两个人才能开始游戏',
        icon: 'none',
        duration: 1500,
        mask: false
      })
    } else {
      const roomId = this.data.roomInfo._id
      wx.cloud.callFunction({
        name: 'drawsthFunctions',
        data: {
          url: 'room/updateInfo',
          data: {
            roomId,
            status: 2,
          }
        }
      })
    }
  }
})